import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;

/**
 * 基本操作实例
 */
public class ZookeeperDemo {
    private String NODE01 = "192.168.100.100:2181";
    private String NODE02 = "192.168.100.110:2181";
    private String NODE03 = "192.168.100.120:2181";
    /*
    创建节点
     */
    @Test
    public void createNode() throws Exception {
        /*1、定制重试策略
        param1：重试间隔时间
        param2：重试最大次数
         */
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 1);
        /*2、获取客户端对象
        param1：服务器列表
        param2：会话超时时间
        param3：连接超时时间
         */
        CuratorFramework client = CuratorFrameworkFactory.newClient(NODE01+","+NODE02+","+NODE03, 1000, 1000, retryPolicy);
        //3.调用start开启客户端操作
        client.start();
        //4.通过create来进行创建节点，并且需要指定节点类型。withMode方法可以指定创建节点类型
        //forPath    指定创建节点的路径和值
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/hello3/world2", "value2".getBytes());
        //5.关闭客户端
        client.close();
    }


    /**
     * 节点下面添加数据与修改是类似的，一个节点下面会有一个数据，新的数据会覆盖旧的数据
     * @throws Exception
     */
    @Test
    public void updateData() throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 1);
        CuratorFramework client = CuratorFrameworkFactory.newClient(NODE01+","+NODE02+","+NODE03,
                        3000, 3000, retryPolicy);
        client.start();
        client.setData().forPath("/hello3", "hahaha".getBytes());
        client.setData().forPath("/hello3/world", "hehehe".getBytes());
        client.close();
    }


    /**
     * 数据查询
     */
    @Test
    public void getNodeData() throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 1);
        CuratorFramework client = CuratorFrameworkFactory.newClient(NODE01+","+NODE02+","+NODE03,
                        3000, 3000, retryPolicy);
        client.start();
        byte[] forPath = client.getData().forPath("/hello3");
        System.out.println(new String(forPath));
        client.close();
    }



    /**
     * zookeeper的watch机制
     * @throws Exception
     */
    @Test
    public void watchNode() throws Exception {
        RetryPolicy policy = new ExponentialBackoffRetry(3000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(NODE01+","+NODE02+","+NODE03, policy);
        client.start();
        // ExecutorService pool = Executors.newCachedThreadPool();
        //设置节点的cache
        TreeCache treeCache = new TreeCache(client, "/hello3");
        //设置监听器和处理过程
        treeCache.getListenable().addListener(new TreeCacheListener(){
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                ChildData data = event.getData();
                if(data !=null){
                    switch (event.getType()) {
                        case NODE_ADDED:
                            System.out.println("NODE_ADDED : "+ data.getPath() +" 数据:"+ new String(data.getData()));
                            break;
                        case NODE_REMOVED:
                            System.out.println("NODE_REMOVED : "+ data.getPath() +" 数据:"+ new String(data.getData()));
                            break;
                        case NODE_UPDATED:
                            System.out.println("NODE_UPDATED : "+ data.getPath() +" 数据:"+ new String(data.getData()));
                            break;
                        default:
                            break;
                    }
                }else{
                    System.out.println( "data is null : "+ event.getType());
                }
            }
        });
        //开始监听
        treeCache.start();
        Thread.sleep(50000000);
    }
}
